from django.core.management.base import BaseCommand
from cmdb.models import Host


class Command(BaseCommand):
    help = '将主机的旧字段数据迁移到新字段'

    def handle(self, *args, **options):
        hosts = Host.objects.all()
        migrated_count = 0

        self.stdout.write(self.style.SUCCESS(f'开始迁移主机数据...共 {hosts.count()} 条记录'))

        for host in hosts:
            updated = False

            # 将 ip 迁移到 public_ip
            if host.ip and (not host.public_ip or host.public_ip == '0.0.0.0'):
                host.public_ip = host.ip
                updated = True
                self.stdout.write(f'  迁移主机 {host.hostname} 的IP数据: {host.ip} -> public_ip')

            # 将 cpu 迁移到 cpu_info
            if host.cpu and not host.cpu_info:
                host.cpu_info = host.cpu
                updated = True
                self.stdout.write(f'  迁移主机 {host.hostname} 的CPU数据: {host.cpu} -> cpu_info')

            # 将 memory 迁移到 memory_info
            if host.memory and not host.memory_info:
                host.memory_info = host.memory
                updated = True
                self.stdout.write(f'  迁移主机 {host.hostname} 的内存数据: {host.memory} -> memory_info')

            # 将 disk 迁移到 disk_info
            if host.disk and not host.disk_info:
                host.disk_info = host.disk
                updated = True
                self.stdout.write(f'  迁移主机 {host.hostname} 的磁盘数据: {host.disk} -> disk_info')

            # 将 os 迁移到 os_version
            if host.os and not host.os_version:
                host.os_version = host.os
                updated = True
                self.stdout.write(f'  迁移主机 {host.hostname} 的操作系统数据: {host.os} -> os_version')

            if updated:
                host.save()
                migrated_count += 1

        self.stdout.write(self.style.SUCCESS(f'数据迁移完成! 共迁移 {migrated_count} 条记录')) 